package com.oto.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.oto.Constants;
import com.oto.model.PackDO;

/**
 * @author xueqiang.mi
 * @since 2010-11-27
 */
@Service
public class PackService extends BaseService {

	public void add(PackDO p) {
		Date now = new Date();
		p.setCrtDate(now);
		p.setModDate(now);

		save(p);
	}

	/**
	 * 根据所有者和所有者查询或创建Pack
	 * 
	 * <pre>
	 * 1. 名称为空时，设置为默认值
	 * 2. 查询Pack，如果结果为空，则创建Pack
	 * 3. 返回结果
	 * </pre>
	 * 
	 * @param name
	 *          为null时，使用默认值
	 * @param owner
	 *          pack的所有者
	 * @return PackDO
	 */
	public PackDO getOrCreate(String name, String owner) {
		name = StringUtils.defaultIfEmpty(name, Constants.DEFAULT_PACK_NAME);
		PackDO p = getPack(name, owner);
		if (p == null) {
			p = new PackDO();
			p.setName(name);
			p.setOwner(owner);
			add(p);
		}
		return p;
	}

	public void del(Long id) {
		delete(PackDO.class, id);
	}

	public PackDO get(Long id) {
		return get(PackDO.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<PackDO> getByUser(String userName) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(PackDO.class);
			query.setFilter("owner == :owner");
			query.setOrdering("rating desc");
			Collection<PackDO> c = pm.detachCopyAll((Collection<PackDO>) query.execute(userName));
			return new ArrayList<PackDO>(c);
		} finally {
			pm.close();
		}
	}

	public PackDO getDefaultPack(String owner) {
		return getPack(Constants.DEFAULT_PACK_NAME, owner);
	}

	@SuppressWarnings("unchecked")
	public PackDO getPack(String name, String owner) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(PackDO.class);
			query.setFilter("name == '" + name + "' && owner == '" + owner + "'");
			Collection<PackDO> c = (Collection<PackDO>) query.execute();
			if (c != null && !c.isEmpty()) { // 返回查询结果的第一个
				return (PackDO) c.toArray()[0];
			}
			return null;
		} finally {
			pm.close();
		}
	}

	public List<PackDO> list() {
		return list(PackDO.class);
	}
}
